package com.example.demo.questions.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.answers.entity.TAnswers;
import com.example.demo.answers.service.ITAnswersService;
import com.example.demo.base.BaseController;
import com.example.demo.dto.QuestionsAnswersDTO;
import com.example.demo.enums.ErrorEnum;
import com.example.demo.questions.entity.TQuestions;
import com.example.demo.questions.service.ITQuestionsService;
import com.example.demo.utils.ZUtils;
import com.lkx.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.patterns.TypePatternQuestions;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 考题表 前端控制器
 * </p>
 *
 * @author zhongz
 * @since 2019-02-16
 */
@RestController
@RequestMapping("/questions/t-questions")
@Slf4j
public class TQuestionsController extends BaseController {

    @Resource
    private ITAnswersService answersService;

    @Resource
    private ITQuestionsService questionsService;

    @PostMapping("/uploadQuestions")
    public Map<String, Object> upload(@RequestBody MultipartFile file) {
        if (file.isEmpty()) {
            return this.fail("未上传文件");
        }
        String keyValue = "考题内容:quesContent,解析:analysis,答案内容:ansContents";
        List<QuestionsAnswersDTO> list;
        try {
            list = ExcelUtil.readXls(file.getBytes(), ExcelUtil.getMap(keyValue), "com.example.demo.dto.QuestionsAnswersDTO");
            // 0.考题表中原有数据要保留
            int count = questionsService.count(null);
            list = list.subList(count, list.size());

            list.parallelStream().forEach(rqa -> {
                TQuestions questions = new TQuestions();
                questions.setId(ZUtils.getUUID());
                // 答案内容list
                List<String> ansContentList = rqa.getAnsContentList();
                // 正确答案ID
                String rightAnswerId = null;
                for (int i = 0; i < ansContentList.size(); i++) {
                    // 1.保存答案
                    String answer = ansContentList.get(i);
                    TAnswers answers = new TAnswers();
                    answers.setId(ZUtils.getUUID());
                    answers.setQuestionId(questions.getId());
                    answers.setAnsContent(answer);
                    answersService.save(answers);
                    if (i == 0) {
                        rightAnswerId = answers.getId();
                    }
                }
                // 2.保存考题
                questions.setRightAnswerId(rightAnswerId);
                questions.setQuesContent(rqa.getQuesContent());
                questions.setAnswerTotalCount(ansContentList.size());
                questions.setAnalysis(rqa.getAnalysis());
                questionsService.save(questions);
            });
        } catch (Exception e) {
            e.printStackTrace();
            return this.fail("读取文件时发生错误");
        }
        return this.success("上传成功");
    }

    /**
     * 获取考题列表
     *
     * @param pagination 页码
     * @param size       每页显示条数
     * @param searchData 查询条件
     * @return
     */
    @GetMapping("/list")
    public Map<String, Object> list(Integer pagination, Integer size, String searchData) {
        log.info("获取考题列表");
        try {
            if (StringUtils.isNotEmpty(searchData)) {
                searchData = URLDecoder.decode(searchData, "UTF8");
            }
            // 查询考题
            Page<TQuestions> page = new Page<>(pagination, size);
            QueryWrapper<TQuestions> questionsQueryWrapper = new QueryWrapper<>();
            // 添加查询条件
            if (StringUtils.isNotEmpty(searchData)) {
                Map tempMap = JSON.parseObject(searchData, Map.class);
                if (tempMap.get("quesContent") != null) {
                    questionsQueryWrapper.like("QUES_CONTENT", tempMap.get("quesContent"));
                }
            }
            IPage<Map<String, Object>> questionsIPage = questionsService.pageMaps(page, questionsQueryWrapper);
            List<Map<String, Object>> questionList = questionsIPage.getRecords();
            questionsIPage.setRecords(this.transList(questionList));
            return success(questionsIPage);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return fail(ErrorEnum.CANT_FIND.getValue());
        }
    }

    /**
     * 获取考题数据
     *
     * @param id
     * @return
     */
    @GetMapping("/ques/{id}")
    public Map<String, Object> ques(@PathVariable String id) {
        QueryWrapper<TQuestions> quesWrapper = new QueryWrapper<>();
        quesWrapper.eq("ID", id);
        Map<String, Object> question = questionsService.getMap(quesWrapper);
        if (question != null) {
            QueryWrapper<TAnswers> answerWrapper = new QueryWrapper<>();
            answerWrapper.eq("QUESTION_ID", question.get("id"));
            List<TAnswers> answersList = answersService.list(answerWrapper);
            StringBuilder wrongAnswers = new StringBuilder();
            StringBuilder wrongAnswerIds = new StringBuilder();
            answersList.parallelStream().forEach(answer -> {
                if (StringUtils.equals(answer.getId(), question.get("rightAnswerId").toString())) {
                    question.put("right", answer.getAnsContent());
                } else {
                    wrongAnswers.append(answer.getAnsContent()).append(" | ");
                    wrongAnswerIds.append(answer.getId()).append("|");
                }
            });
            question.put("wrong", StringUtils.substring(wrongAnswers.toString(), 0, wrongAnswers.toString().length() - 3));
            question.put("wrongIds", wrongAnswerIds.toString());
        }
        return success(question);
    }

    @PostMapping("")
    public Map<String, Object> update(@Valid TQuestions questions, BindingResult result) {
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError error : allErrors) {
                return fail(error.getDefaultMessage());
            }
        }

        return success();
    }

    /**
     * 完善list中的内容，用于前台展示
     *
     * @param questionList 考题list
     * @return mapList
     */
    private List<Map<String, Object>> transList(List<Map<String, Object>> questionList) {
        for (Map<String, Object> map : questionList) {
            // 通过考题id查询对应的答案
            QueryWrapper<TAnswers> answersQueryWrapper = new QueryWrapper<>();
            answersQueryWrapper.eq("QUESTION_ID", map.get("id"));
            List<TAnswers> answersList = answersService.list(answersQueryWrapper);
            StringBuilder wrongAnswers = new StringBuilder();
            for (TAnswers answer : answersList) {
                if (StringUtils.equals(answer.getId(), map.get("rightAnswerId").toString())) {
                    map.put("right", answer.getAnsContent());
                } else {
                    wrongAnswers.append(answer.getAnsContent()).append(" | ");
                }
            }
            map.put("wrong", StringUtils.substring(wrongAnswers.toString(), 0, wrongAnswers.toString().length() - 3));
        }
        return questionList;
    }
}
